package com.dongbao.service;

import com.alibaba.fastjson.JSON;
import com.dongbao.core.config.MyState;
import com.dongbao.data.Datacenter;
import com.dongbao.entity.MqMessage;
import com.dongbao.util.IdeaApiUtil;
import com.intellij.notification.NotificationType;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.HashMap;
import java.util.Map;

public class MyMqttClient {

    public static MqttClient mqttClient = null;
    private static MemoryPersistence memoryPersistence = null;
    private static MqttConnectOptions mqttConnectOptions = null;

    public static String TOPIC_PREFIX = "DHG:";

    public static String TOPIC_ALL = "all_topic";


    static {
        init(Datacenter.clientIp);
    }


    public static void init(String clientId) {
        //初始化连接设置对象
        mqttConnectOptions = new MqttConnectOptions();
        //初始化MqttClient
        if (null != mqttConnectOptions) {
//			true可以安全地使用内存持久性作为客户端断开连接时清除的所有状态
            mqttConnectOptions.setCleanSession(true);
//			设置连接超时
            mqttConnectOptions.setConnectionTimeout(30);
//			客户端名字
            mqttConnectOptions.setUserName(ipConvertName(clientId));
//			设置持久化方式
            memoryPersistence = new MemoryPersistence();
            if (null != memoryPersistence && null != clientId) {
                try {
                    mqttClient = new MqttClient(MyState.getInstance().getConfig().getMqUrlPath(), clientId, memoryPersistence);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    IdeaApiUtil.showErrNotification("MQ客户端链接失败，请检查MQ服务端地址与本地客户端IP是否正确", Datacenter.project);
                    e.printStackTrace();
                    return ;
                }
            } else {

            }
        } else {
            System.out.println("mqttConnectOptions对象为空");
        }

        System.out.println(mqttClient.isConnected());
        //设置连接和回调
        IdeaApiUtil.showNotification("开始连接MQTT服务", NotificationType.INFORMATION,Datacenter.project);
        if (null != mqttClient) {
            if (!mqttClient.isConnected()) {

                //创建回调函数对象
                MqttRecieveCallback mqttReceriveCallback = new MqttRecieveCallback();
                //客户端添加回调函数
                mqttClient.setCallback(mqttReceriveCallback);
                //创建连接
                try {
                    System.out.println("创建连接");
                    mqttClient.connect(mqttConnectOptions);
                    IdeaApiUtil.showInfoNotification("DHG_MQTT服务链接成功",Datacenter.project);
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    IdeaApiUtil.showErrNotification("创建链接错误"+e.getMessage(),Datacenter.project);
                }
            }else{
                IdeaApiUtil.showErrNotification("DHG_MQTT服务链接失败",Datacenter.project);
            }
        } else {
            System.out.println("mqttClient为空");
        }
        System.out.println(mqttClient.isConnected());
    }

    //	关闭连接
    public static void closeConnect() {
        //关闭存储方式
        if (null != memoryPersistence) {
            try {
                memoryPersistence.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                IdeaApiUtil.showErrNotification("MQ客户端链接失败：关闭 MemoryPersistence 失败", Datacenter.project);
                e.printStackTrace();
            }
        } else {
            System.out.println("memoryPersistence is null");
        }

//		关闭连接
        if (null != mqttClient) {
            if (mqttClient.isConnected()) {
                try {
                    mqttClient.disconnect();
                    mqttClient.close();
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                System.out.println("mqttClient is not connect");
            }
        } else {
            System.out.println("mqttClient is null");
        }
    }

    /**
     * 发布消息
     * */
    public void publishMessage(String pubTopic, MqMessage messageBean, int qos) {
        if (null != mqttClient && mqttClient.isConnected()) {
            String message= JSON.toJSONString(messageBean);
            System.out.println("发布消息   " + mqttClient.isConnected());
            System.out.println("id:" + mqttClient.getClientId());
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(qos);
            mqttMessage.setPayload(message.getBytes());

            MqttTopic topic = mqttClient.getTopic(pubTopic);

            if (null != topic) {
                try {
                    MqttDeliveryToken publish = topic.publish(mqttMessage);
                    if (!publish.isComplete()) {
                        System.out.println("消息发布成功");
                    }
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        } else {
            reConnect();
        }

    }

    /**
     * 发布消息
     * */
    public void publishMessage(String pubTopic, String message, int qos) {
        if (null != mqttClient && mqttClient.isConnected()) {
            System.out.println("发布消息   " + mqttClient.isConnected());
            System.out.println("id:" + mqttClient.getClientId());
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(qos);
            mqttMessage.setPayload(message.getBytes());

            MqttTopic topic = mqttClient.getTopic(pubTopic);

            if (null != topic) {
                try {
                    MqttDeliveryToken publish = topic.publish(mqttMessage);
                    if (!publish.isComplete()) {
                        System.out.println("消息发布成功");
                    }
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        } else {
            reConnect();
        }

    }

    //	重新连接
    public static void reConnect() {
        if (null != mqttClient) {
            if (!mqttClient.isConnected()) {
                if (null != mqttConnectOptions) {
                    try {
                        mqttClient.connect(mqttConnectOptions);
                        IdeaApiUtil.showInfoNotification("MQ服务重置成功",Datacenter.project);
                    } catch (MqttException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    IdeaApiUtil.showInfoNotification("mqttConnectOptions is null",Datacenter.project);
                    System.out.println("mqttConnectOptions is null");
                }
            } else {
                IdeaApiUtil.showInfoNotification("[不需要刷新]:mqttClient is null or connect",Datacenter.project);
            }
        } else {
            init("123");
        }

    }

    //	订阅主题
    public void subTopic(String topic) {
        if (null != mqttClient && mqttClient.isConnected()) {
            try {
                mqttClient.subscribe(topic, 1);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            System.out.println("mqttClient is error");
        }
    }


    //	清空主题
    public void cleanTopic(String topic) {
        if (null != mqttClient && !mqttClient.isConnected()) {
            try {
                mqttClient.unsubscribe(topic);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            System.out.println("mqttClient is error");
        }
    }

    public static String ipConvertName(String ip){
        Map<String,String> ipMap=new HashMap<String,String>();
        ipMap.put("192.168.2.72","黄涛");
        ipMap.put("192.168.2.207","陈崇彬");
        ipMap.put("192.168.2.23","陈利辉");
        ipMap.put("192.168.2.79","曹庭华");
        ipMap.put("192.168.2.73","车晓银");
        ipMap.put("192.168.2.153","陈易易");
        ipMap.put("192.168.2.81","蔡祖杰");
        ipMap.put("192.168.2.194","郭冬泉");
        ipMap.put("192.168.2.100","何威");
        ipMap.put("192.168.2.111","黄伟峰");
        ipMap.put("192.168.2.58","黄旭志");
        ipMap.put("192.168.2.59","黄友顺");
        ipMap.put("192.168.2.64","吕锦辉");
        ipMap.put("192.168.2.184","梁凯");
        ipMap.put("192.168.2.187","李敏");
        ipMap.put("192.168.2.74","李桥妹");
        ipMap.put("192.168.2.127","罗润林");
        ipMap.put("192.168.2.50","刘弦");
        ipMap.put("192.168.2.53","李战");
        ipMap.put("192.168.2.157","莫锦涛");
        ipMap.put("192.168.2.189","马泽铭");
        ipMap.put("192.168.2.41","帅东华");
        ipMap.put("192.168.2.205","深圳研发");
        ipMap.put("192.168.2.66","谭倩怡");
        ipMap.put("192.168.2.102","吴建生");
        ipMap.put("192.168.2.84","吴泳滨");
        ipMap.put("192.168.2.83","王志坤");
        ipMap.put("192.168.2.123","徐亚成");
        ipMap.put("192.168.2.54","叶松");
        ipMap.put("192.168.2.173","杨杏存");
        ipMap.put("192.168.2.185","张晓宇");
        ipMap.put("192.168.2.63","黎如飞");
        if(ipMap.containsKey(ip)){
            return ipMap.get(ip);
        }
        return "未知";
    }

}

